﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        if (txtTenDangNhap.Text.Equals(""))
        {
            FailureText.Text = "Vui lòng nhập tên đăng nhập";
            return;
        }
        if (txtMatKhau.Text.Equals(""))
        {
            FailureText.Text = "Vui lòng nhập mật khẩu";
            return;
        }
        if (Membership.ValidateUser(txtTenDangNhap.Text, txtMatKhau.Text))
        {
            FormsAuthentication.RedirectFromLoginPage(txtTenDangNhap.Text, false);

            // Get a reference to the currently logged on user
            MembershipUser currentUser = Membership.GetUser(txtTenDangNhap.Text);
            // Determine the currently logged on user's UserId value  
            Guid currentUserId = (Guid)currentUser.ProviderUserKey;
            Session.Add("g_UserId", currentUserId);

            //luu thong tin dang nhap vao cookie
            HttpCookie aCookie = new HttpCookie("UserId");
            aCookie.Value = currentUserId.ToString();
            aCookie.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Add(aCookie);

            //lay roles
            string[] strRole = Roles.GetRolesForUser(txtTenDangNhap.Text);
            Session.Add("RoleForUser", strRole[0]);

            //luu thong tin dang nhap vao cookie
            aCookie = new HttpCookie("RoleForUser");
            aCookie.Value = strRole[0];
            aCookie.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Add(aCookie);

            Response.Redirect("admin/Default.aspx");
        }
    }
}
